from rqalpha.apis import *
import time
from rqalpha.environment import Environment
from rqalpha.my_factors.reform_data import split_factors, read_adj_factor_price
from rqalpha import run_func

config = {
    "base": {
        "start_date": "2021-07-31",
        "end_date": "2021-07-31",
        "frequency": "1d",
        "accounts": {
            "stock": 100000000
        }
    },

    "extra": {
        "log_level": "info",
    },

    "mod": {
        "my_backtest": {
            "enabled": True
        },
        "sys_analyser": {
            "enabled": True,
            "benchmark": "000905.XSHG",
            # "plot": True,
            "plot": False,
            "report_save_path": "C:\\Users\\huajia\Desktop\\rqalpha4\\rqalpha\\plot_result"
        },
        "sys_simulation": {
            "enabled": True,
            "matching_type": "current_bar",
            "volume_limit": False,
            "inactive_limit": True,
            "price_limit": True
        },
        "sys_accounts": {
            "enabled": True,
            "validate_stock_position": False,
            "stock_t1": False
        },
        "incremental": {
            "enabled": True,
            "strategy_id": "1",
            # 是否启用 csv 保存 feeds 功能，可以设置为 MongodbRecorder
            "recorder": "CsvRecorder",
            # 持久化数据输出文件夹
            "persist_folder": "C:\\Users\huajia\\Desktop\\rqalpha4\\rqalpha\\incremental_result",
            # "persist_folder": None,
            # mongodb
            "mongo_url": "mongodb://localhost",
            "mongo_dbname": "rqalpha_records",
        }
    }
}


def run_bt(config, my_defines):
    # 在这个方法中编写任何的初始化逻辑。context对象将会在你的算法策略的任何方法之间做传递。
    def init(context):
        logger.info("init------------")

    def before_trading(context):
        # 在init中定义的context.s1在开启increment开启后会保持一直不变，那么可以在before中定义
        factor = my_defines['factor_df']
        # print(symbol)
        logger.info("get factors---")
        # print(context.now, type(context.now))
        # time.sleep(50)
        # dt = my_defines['config.base']['start_date']
        dt = pd.to_datetime(context.now).strftime('%Y-%m-%d')
        print(dt)
        last_li = my_defines['last_li']
        q1, q2, q3, q4, q5, q_last, factor_s = split_factors(factor, dt, last_li)
        my_defines['q1'] = q1
        my_defines['sub_factor'] = factor_s

    def open_auction(context, bar_dict):
        print('open_auction ++++++++')

        for group in [1]:
            if my_defines['is_first_trade']:
                print('first_run -------- ')
                for order_book_id in my_defines['q{}'.format(group)][0:100]:
                    order_target_percent(order_book_id, 0.01)
                my_defines['is_first_trade'] = False
            else:
                print('second_run -------- ')
                factor_s = my_defines['sub_factor']
                new_li = my_defines['q{}'.format(group)]
                old_li = list(context.portfolio.positions.keys())
                new_li_set = set(new_li)
                old_li_set = set(old_li)
                if len(new_li_set & old_li_set) >= 90:
                    print('section 1')
                    need_buy_li = list(new_li_set - old_li_set)
                    need_sell_li = list(old_li_set - new_li_set)
                else:
                    print('section 2')
                    need_buy_li = list(new_li_set - old_li_set)
                    need_sell_li = list(old_li_set - new_li_set)

                    buy_factor = factor_s[factor_s.index.isin(need_buy_li)]
                    need_buy_li = buy_factor.sort_values(ascending=False).head(10).index.tolist()

                    sell_factor = factor_s[factor_s.index.isin(need_sell_li)]
                    need_sell_li = sell_factor.sort_values(ascending=True).head(10).index.tolist()
                print(need_buy_li)
                print(need_sell_li)
                # for order_book_id in need_sell_li:
                #     if order_book_id in old_li and \
                #             context.portfolio.positions[order_book_id].quantity != 0:
                #         order_target_percent(order_book_id, 0)
                # for order_book_id in need_buy_li:
                #     order_target_percent(order_book_id, 0.01)

                for order_book_id in need_sell_li:
                    if order_book_id in context.portfolio.positions.keys() and \
                            context.portfolio.positions[order_book_id].quantity != 0:
                        # price = bar_dict[order_book_id].open
                        order_target_percent(order_book_id, 0)
                for order_book_id in need_buy_li:
                    order_target_percent(order_book_id, 0.01)

    def handle_bar(context, bar_dict):
        pass

    def after_trading(context):
        print('after trading----------------')
        # li = [i for i in my_defines['queue1'] if i not in context.portfolio.positions.keys()]
        # for i in li:
        #     del my_defines['queue1'][i]

    run_func(config=config, init=init, open_auction=open_auction, before_trading=before_trading, handle_bar=handle_bar,
             after_trading=after_trading, my_defines=my_defines)


